import cryptoFramework from '@ohos.security.cryptoFramework';
import util from '@ohos.util';

const BASE64 = new util.Base64Helper();
const FIXED_KEY = "hsylgwk-20120101"; // 原始密钥（14字节）

/**
 * 03 AES加解密
 */
export class AesUtils {
  /**
   * 初始化AES密钥（处理密钥长度问题）
   */
  static async initAesKey(): Promise<cryptoFramework.SymKey | null> {
    try {
      // 将密钥转为字节数组并填充到16字节（AES-128）
      const encoder = new util.TextEncoder();
      let keyBytes = encoder.encode(FIXED_KEY);

      // 密钥长度修正（不足16字节补零，超出则截断）
      const targetLength = 16;
      const validKeyBytes = new Uint8Array(targetLength);
      validKeyBytes.set(keyBytes.slice(0, targetLength));

      // 创建对称密钥
      const keyBlob: cryptoFramework.DataBlob = { data: validKeyBytes };
      const generator = cryptoFramework.createSymKeyGenerator('AES128');
      return await generator.convertKey(keyBlob);
    } catch (err) {
      console.error(`AES密钥初始化失败: ${JSON.stringify(err)}`);
      return null;
    }
  }

  /**
   * AES加密（返回Base64字符串）
   */
  static async encrypt(plainText: string): Promise<string | null> {
    if (!plainText) return null;

    try {
      const symKey = await AesUtils.initAesKey();
      if (!symKey) return null;

      // 创建Cipher实例
      const cipher = cryptoFramework.createCipher('AES128|ECB|PKCS5');
      await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey,null);

      // 加密并编码为Base64
      const input: cryptoFramework.DataBlob = { data: new util.TextEncoder().encode(plainText) };
      const encryptedData = await cipher.doFinal(input);
      return BASE64.encodeToStringSync(encryptedData.data);
    } catch (err) {
      console.error(`加密失败: ${JSON.stringify(err)}`);
      return null;
    }
  }

  /**
   * AES解密（输入去掉00.00.03后的Base64字符串）
   */
  static async decrypt(cipherText: string): Promise<string> {
    if (!cipherText) return "";

    try {
      const symKey = await AesUtils.initAesKey();
      if (!symKey) return "";

      // 创建Cipher实例
      const cipher = cryptoFramework.createCipher('AES128|ECB|PKCS5');
      await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey,null);

      // 解码Base64并解密
      const decoded = BASE64.decodeSync(cipherText);
      const input: cryptoFramework.DataBlob = { data: decoded };
      const decryptedData = await cipher.doFinal(input);
      return new util.TextDecoder().decode(decryptedData.data);
    } catch (err) {
      console.error(`解密失败: ${JSON.stringify(err)}`);
      return "";
    }
  }
}

// // 使用示例
// async function testAes() {
//   const original = "Hello HarmonyOS";
//
//   // 加密
//   const encrypted = await AesUtils.encrypt(original);
//   console.log("加密结果:", encrypted); // 示例输出: "pm5QLo+aXm4FMd49kzrk3g=="
//
//   // 解密
//   const decrypted = await AesUtils.decrypt(encrypted!);
//   console.log("解密结果:", decrypted); // 输出: "Hello HarmonyOS"
// }
//
// testAes();